import React, { useState, useEffect, useCallback, useRef } from 'react';
import './CustomerServiceChat.css';

// 假设这是从服务器获取的联想问题列表
const suggestionList = [
    '订单查询',
    '退货政策',
    '联系我们',
    '常见问题',
    '账户帮助',
    '支付方式'
];

// 定义表情列表
const emojiList = [
    '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '🥲', '😊',
    '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙',
    '😚', '😋', '😛', '😜', '🤪', '😝', '🤑', '🤗', '🤭', '🤫',
    '🤔', '🤐', '🤨', '😐', '😑', '😶', '😏', '😒', '🙄', '😬',
    '🤥', '😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕', '🤢',
    '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '😵‍💫', '🤯', '🤠', '🥳',
    '🥸', '😎', '🤓', '🧐', '😕', '😟', '🙁', '☹️', '😮', '😯',
    '😲', '😳', '🥺', '😦', '😧', '😨', '😰', '😥', '😢', '😭',
    '😱', '😖', '😣', '😞', '😓', '😩', '😫', '🥱', '😤', '😡',
    '😠', '🤬', '🤯', '🥵', '🥶', '😈', '👿', '👹', '👺', '💀',
    '☠️', '👻', '👽', '👾', '🤖', '💩', '🤡', '👮', '👮‍♀️', '👨‍⚖️',
    '💂', '💂‍♀️', '🕵️', '🕵️‍♀️', '👷', '👷‍♀️', '🚜', '🏍️', '🚑', '🚒'
];

const CustomerServiceChat = () => {
    const [messages, setMessages] = useState([]);
    const [inputValue, setInputValue] = useState('');
    const wsRef = useRef(null);
    const [suggestions, setSuggestions] = useState([]);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const [showEmojiPicker, setShowEmojiPicker] = useState(false);
    const [showChatModal, setShowChatModal] = useState(false);
    const fileInputRef = useRef(null);

    // 在 useEffect 中监听 WebSocket 消息
    useEffect(() => {
        const socket = new WebSocket('ws://localhost:8080');

        socket.onmessage = (event) => {
            const message = JSON.parse(event.data);
            if (message.type === 'suggestion') {
                // 更新联想建议列表
                setSuggestions(message.suggestions);
                setShowSuggestions(true);
            } else {
                // 更新聊天消息列表
                setMessages((prevMessages) => [
                    ...prevMessages,
                    { name: '客服-1008', content: message.content, isUser: false },
                ]);
            }
        };

        // 设置 WebSocket
        wsRef.current = socket;

        // 清理连接
        return () => {
            socket.close();
        };
    }, []);

    // 处理输入框变化
    const handleInputChange = useCallback((e) => {
        const value = e.target.value;
        setInputValue(value);

        // 根据输入值过滤联想问题列表
        if (value.trim() === '') {
            setSuggestions([]);
            setShowSuggestions(false);
        } else {
            const filteredSuggestions = suggestionList.filter(suggestion =>
                suggestion.toLowerCase().startsWith(value.toLowerCase())
            );
            setSuggestions(filteredSuggestions);
            setShowSuggestions(true);
        }
    }, []);

    // 选择联想问题
    const handleSuggestionClick = useCallback((suggestion) => {
        setInputValue(suggestion);
        setSuggestions([]);
        setShowSuggestions(false);

        // 发送联想问题作为消息
        if (wsRef.current) {
            const message = {
                type: 'chat',
                content: suggestion,
            };
            wsRef.current.send(JSON.stringify(message));

            // 更新消息列表
            setMessages((prevMessages) => [...prevMessages, { name: '菲菲公主', content: suggestion, isUser: true }]);
        }
    }, []);

    // 发送消息
    const handleSendMessage = useCallback(() => {
        if (inputValue.trim() !== '' && wsRef.current) {
            const message = {
                type: 'chat',
                content: inputValue,
            };

            // 发送消息到 WebSocket 服务器
            wsRef.current.send(JSON.stringify(message));

            // 更新消息列表
            setMessages((prevMessages) => [...prevMessages, { name: '九日', content: inputValue, isUser: true }]);

            // 清空输入框
            setInputValue('');
        }
    }, [inputValue]);

    // 处理键盘按下事件
    const handleKeyDown = useCallback((e) => {
        if (e.key === 'Enter') {
            handleSendMessage();
        }
    }, [handleSendMessage]);

    // 处理表情选择
    const handleEmojiClick = useCallback((emoji) => {
        setInputValue((prevValue) => prevValue + emoji);
        setShowEmojiPicker(false);
    }, []);

    // 切换表情选择器显示状态
    const toggleEmojiPicker = useCallback(() => {
        setShowEmojiPicker((prevState) => !prevState);
    }, []);

    // 切换聊天弹框显示状态
    const toggleChatModal = useCallback(() => {
        setShowChatModal((prevState) => !prevState);
    }, []);

    // 处理文件选择
    const handleFileSelect = useCallback((e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event) => {
                const imageData = event.target?.result;
                if (imageData) {
                    if (wsRef.current) {
                        const message = {
                            type: 'chat',
                            content: `<img src="${imageData}" alt="Uploaded Image" />`,
                        };
                        wsRef.current.send(JSON.stringify(message));

                        // 更新消息列表
                        setMessages((prevMessages) => [
                            ...prevMessages,
                            { name: '九日', content: `<img  style={{ width: '40px', height: '40px' }} src="${imageData}" alt="Uploaded Image" />`, isUser: true },
                        ]);
                    }
                }
            };
            reader.readAsDataURL(file);
        }
        // 清空文件输入框
        fileInputRef.current.value = '';
    }, []);

    // 触发文件选择对话框
    const handleUploadClick = useCallback(() => {
        fileInputRef.current.click();
    }, []);

    return (
        <div>
            <button className="open-chat-button" onClick={toggleChatModal}>?</button>
            {showChatModal && (
                <div className="chat-modal">
                    <div className="chat-modal-overlay" onClick={toggleChatModal} />
                    <div className="chat-container">
                        {/* 聊天头部 */}
                        <div className="chat-header">
                            <h1>在线客服</h1>
                        </div>

                        {/* 聊天窗口 */}
                        <div className="chat-window">
                            {messages.map((message, index) => (
                                <div
                                    key={index}
                                    className={`message ${message.isUser ? 'user-message' : 'server-message'}`}
                                >
                                    <img
                                        src={
                                            message.isUser
                                                ? 'https://t9.baidu.com/it/u=961441239,2656627414&fm=3031&app=3031&size=f242,150&n=0&f=JPEG&fmt=auto?s=DF90ED09E932F7ED5C285DDB0300C0A0&sec=1736874000&t=281777903ab3ccaa54ded8f124ed16e6'
                                                : 'https://t9.baidu.com/it/u=3741310215,870289439&fm=217&app=126&size=f242,150&n=0&f=JPEG&fmt=auto?s=6BE63363052696A80388459B0300A081&sec=1736874000&t=6a4c870a7af6a1bd371c3bf3c6aa9297'
                                        }
                                        alt="avatar"
                                        className="avatar"
                                    />
                                    <div className="message-name">{message.name}</div>
                                    <div className="message-content">
                                        <div className="message-text" dangerouslySetInnerHTML={{ __html: message.content }} />
                                    </div>
                                </div>
                            ))}
                        </div>

                        {/* 聊天输入框 */}
                        <div className="chat-input">
                            <button onClick={toggleEmojiPicker}>😀</button>
                            <button onClick={handleUploadClick}>上传</button>
                            <input
                                type="file"
                                ref={fileInputRef}
                                style={{ display: 'none' }}
                                onChange={handleFileSelect}
                            />
                            <input
                                type="text"
                                value={inputValue}
                                onChange={handleInputChange}
                                onKeyDown={handleKeyDown}
                                placeholder="请输入要输入的内容"
                            />
                            {/* 联想建议列表 */}
                            {showSuggestions && (
                                <ul className="suggestions-list">
                                    {suggestions.map((suggestion, index) => (
                                        <li key={index} onClick={() => handleSuggestionClick(suggestion)}>
                                            {suggestion}
                                        </li>
                                    ))}
                                </ul>
                            )}
                            {/* 表情选择器 */}
                            {showEmojiPicker && (
                                <div className="emoji-picker">
                                    {emojiList.map((emoji, index) => (
                                        <span key={index} onClick={() => handleEmojiClick(emoji)}>
                                            {emoji}
                                        </span>
                                    ))}
                                </div>
                            )}
                            <button onClick={handleSendMessage}>发送</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default CustomerServiceChat;